package gw.com.android.presenter.http;

import android.text.TextUtils;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.ui.me_concern.AnalystData;
import gw.com.android.utils.CacheUtils;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 我的关注-分析师列表
 *
 * @author hank
 * @since 2018-6-1
 */
public class MyConcernRequest {

    /**
     * 添加关注
     */
    public static final int CONST_ADD_FOLLOW = 1;
    /**
     * 取消关注
     */
    public static final int CONST_CANCEL_FOLLOW = 0;

    private static final String CONST_ANALYST_TYPE = "2";

    /**
     * 添加关注，或者取消关注
     *
     * @param callBack
     * @param userId    用户账户
     * @param analystNo 分析师账户
     * @param ifFollow  1,关注，0，取消关注
     */
    public void addOrRemoveFollowedAnalystList(final String userId, final String analystNo, final int ifFollow, final HttpCallback<String> callBack) {
        acquireChatToken(new ChatTokenRequest.OnTokenListener() {//必须先获得token
            @Override
            public void onSuccess(String token) {
                realAddOrRemoveFollowedAnalystList(userId, analystNo, ifFollow, token, callBack);
            }

            @Override
            public void onFailure(Exception e) {
                if (callBack != null) {
                    callBack.onFailure(e);
                }
            }
        });
    }

    /**
     * 获取用户关注的分析师列表
     *
     * @param callBack
     */
    public void getFollowedAnalystList(final String userId, final HttpCallback<List<AnalystData>> callBack) {
        acquireChatToken(new ChatTokenRequest.OnTokenListener() {//必须先获得token
            @Override
            public void onSuccess(String token) {
                realGetFollowedAnalystList(userId, token, callBack);
            }

            @Override
            public void onFailure(Exception e) {
                if (callBack != null) {
                    callBack.onFailure(e);
                }
            }
        });
    }


    /**
     * 获取所有分析师列表
     *
     * @param callBack
     */
    public void getAllAnalystList(final HttpCallback<List<AnalystData>> callBack) {
        acquireChatToken(new ChatTokenRequest.OnTokenListener() {//必须先获得token
            @Override
            public void onSuccess(String token) {
                realGetAllAnalystList(token, callBack);
            }

            @Override
            public void onFailure(Exception e) {
                if (callBack != null) {
                    callBack.onFailure(e);
                }
            }
        });
    }

    private void acquireChatToken(ChatTokenRequest.OnTokenListener listener) {
        new ChatTokenRequest().acquire(listener);
    }

    private void realAddOrRemoveFollowedAnalystList(final String userId, String analystNo, final int ifFollow, final String token, final HttpCallback<String> callback) {
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/user/setTeacherFollower";
        Https https = new Https().url(url)
//                .addParam("groupType", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_GROUP_TYPE))
                .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                .addParam("userId", userId)
                .addParam("analystNo", analystNo)
                .addParam("isFollow", "" + ifFollow)
                .addParam("type", CONST_ANALYST_TYPE)//为了区分直播间关注，以及帖子关注的分析师，后台设置了这个参数，我们app端关注的分析师，全部都传type=2
                //难道应该传1？
                .addParam("token", token);

        //遍历参数
        Map<String, String> map = https.getParam();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            Log.d("AddOrRemoveFollowed", entry.getKey() + ":" + entry.getValue());
        }

        https.post(new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, final String result, int code) {
                final String s = (ifFollow == MyConcernRequest.CONST_ADD_FOLLOW) ? "关注" : "取消关注";
                Log.d("addOrRemoveFollowed", s + "分析师的结果为：" + result);
                if (ifFollowSucceed(result)) {
                    callback.onSuccess("true");
                } else {
                    callback.onSuccess("false");
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {
                if (callback != null) {
                    callback.onFailure(e);
                }
            }
        });
    }

    private boolean ifFollowSucceed(String result) {
        boolean succeed;
        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONObject data = jsonObject.optJSONObject("data");
            succeed = data.getBoolean("isOK");
            String userNo = data.getString("userNo");
            Log.d("ifFollowSucced", "" + userNo + "-" + succeed);

        } catch (JSONException e) {
            succeed = false;
        } catch (Exception e) {
            succeed = false;
        }
        return succeed;
    }

    private void realGetFollowedAnalystList(final String userId, final String token, final HttpCallback<List<AnalystData>> callback) {
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/user/getFollowedTeachers";
        new Https().url(url)
//                .addParam("groupType", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_GROUP_TYPE))
                .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                .addParam("userId", userId)
                .addParam("token", token)
                .addParam("type", CONST_ANALYST_TYPE)
                .get(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        Log.d("getFollowedAnalystList", "获取用户关注的分析师列表：" + result);
                        List<AnalystData> list = parseFollowedAnalyst(result, false);
//                        if (list == null) {//测试数据
//                            list = new ArrayList<>();
//                            for (int i = 0; i < 10; i++) {
//                                list.add(new AnalystData("test" + i));
//                            }
//                        }
                        callback.onSuccess(list);//解析完数据之后，就回调
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        if (callback != null) {
                            callback.onFailure(e);
                        }
                    }
                });
    }

    private void realGetAllAnalystList(final String token, final HttpCallback<List<AnalystData>> callback) {
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/user/getAnalystList";
        new Https().url(url)
//                .addParam("groupType", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_GROUP_TYPE))
                .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                .addParam("systemCategory", "hx")
                .addParam("type", CONST_ANALYST_TYPE)
                .addParam("token", token)
                .get(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        Log.d("realGetAllAnalystList", "" + result);
                        List<AnalystData> list = parse(result, false);

//                        if (list == null) {
//                            list = new ArrayList<>();
//                            for (int i = 0; i < 10; i++) {
//                                list.add(new AnalystData("test" + i));
//                            }
//                        }

                        callback.onSuccess(list);//解析完数据之后，就回调
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        if (callback != null) {
                            callback.onFailure(e);
                        }
                    }
                });
    }

    public List<AnalystData> getAllAnalystListSync(String token) {
        String cache = CacheUtils.readFile(CacheUtils.CACHE_ALL_ANALYST_LIST_FILE);
        if (!TextUtils.isEmpty(cache)) {
            return parse(cache, false);
        }
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/user/getAnalystList";
        try {
            Response response = new Https().url(url)
                    .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                    .addParam("systemCategory", "hx")
                    .addParam("type", CONST_ANALYST_TYPE)
                    .addParam("token", token)
                    .get();
            if (response != null && response.isSuccessful()) {
                return parse(response.body().string(), true);
            }
        } catch (IOException ignore) {
        }
        return null;
    }

    /**
     * 解析来自getAnalystList的字符串
     *
     * @param str
     * @param cache
     * @return
     */
    private List<AnalystData> parse(String str, boolean cache) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONArray dataArr = jsonObject.optJSONArray("data");
            if (dataArr != null && dataArr.length() > 0) {
                List<AnalystData> list = new ArrayList<>();
                for (int i = 0; i < dataArr.length(); i++) {
                    JSONObject itemJson = dataArr.optJSONObject(i);
                    if (itemJson == null) {
                        continue;
                    }
                    AnalystData analystData = new AnalystData();
                    analystData._id = itemJson.getString("_id");
                    analystData.position = itemJson.getString("position");

                    analystData.introduction = itemJson.getString("introduction");
                    analystData.avatar = itemJson.getString("avatar");
                    analystData.wechatCode = itemJson.getString("wechatCode");
                    analystData.wechatCodeImg = itemJson.getString("wechatCodeImg");
                    analystData.winRate = itemJson.getString("winRate");
                    analystData.gain = itemJson.getString("gain");
                    analystData.tag = itemJson.getString("tag");
                    analystData.userNo = itemJson.getString("userNo");
                    analystData.earningsM = itemJson.getString("earningsM");
                    analystData.userName = itemJson.getString("userName");
                    analystData.accountNo = itemJson.getString("accountNo");

                    list.add(analystData);
                }
                if (cache) {
                    CacheUtils.writeFile(CacheUtils.CACHE_ALL_ANALYST_LIST_FILE, str);
                }
                return list;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析来自getFollowedAnalyst的字符串
     *
     * @param str
     * @param cache
     * @return
     */
    private List<AnalystData> parseFollowedAnalyst(String str, boolean cache) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONArray dataArr = jsonObject.optJSONArray("data");
            if (dataArr != null && dataArr.length() > 0) {
                List<AnalystData> list = new ArrayList<>();
                for (int i = 0; i < dataArr.length(); i++) {
                    JSONObject itemJson = dataArr.optJSONObject(i);
                    if (itemJson == null) {
                        continue;
                    }
                    int valid = itemJson.optInt("valid");
                    if (valid == 0) {
                        continue;
                    }
                    AnalystData analystData = new AnalystData();
                    analystData._id = itemJson.getString("_id");
                    analystData.position = itemJson.getString("position");
                    analystData.avatar = itemJson.getString("avatar");
                    analystData.userNo = itemJson.getString("userNo");
                    analystData.userName = itemJson.getString("userName");
                    analystData.winRate = itemJson.getString("winRate");
                    analystData.gain = itemJson.getString("gain");
                    analystData.status = itemJson.getInt("status");
                    analystData.valid = itemJson.getInt("valid");
                    analystData.accountNo = itemJson.getString("accountNo");
                    list.add(analystData);
                }
                if (cache) {
                    CacheUtils.writeFile(CacheUtils.CACHE_FOLLOWED_ANALYST_LIST_FILE, str);
                }
                return list;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<AnalystData> fetchFollowedAnalystLocal() {
        String str = CacheUtils.readFile(CacheUtils.CACHE_FOLLOWED_ANALYST_LIST_FILE);
        return parseFollowedAnalyst(str, false);
    }

}
